#include"FindDirDialog.h"
#include <QtDebug>
static const char* SuffixArray[]={"cpp","cxx","c","cc","h","idl","php","py","js"};
FindDir::FindDir(QWidget* parent):QDialog(parent)
{
	ui.setupUi(this);
	ui.Suffix->addItem("C++(*.cpp)");
	ui.Suffix->addItem("C++(*.cxx)");
    ui.Suffix->addItem("C(*.c)");
    ui.Suffix->addItem("C(*.cc)");
    ui.Suffix->addItem("C/C++ header(*.h)");
    ui.Suffix->addItem("IDL File(*.idl)");
    ui.Suffix->addItem("PHP(*.php)");
    ui.Suffix->addItem("Python(*.py)");
    ui.Suffix->addItem("Javascript(*.js)");
	connect(ui.OkBox,SIGNAL(clicked()),this,SLOT(StartFindText()));
	connect(ui.OpenDirButton,SIGNAL(clicked()),this,SLOT(OpenDirDialog()));
	connect(ui.ShowFindResult,SIGNAL(itemDoubleClicked( QListWidgetItem* )),this,SLOT(GetFileName(QListWidgetItem*)));
}
 
FindDir::~FindDir(void)
{


}

void FindDir::GetFileName(QListWidgetItem* Item)
{
	QString ItemText;
        int rownum;
        int lineNum;
        ItemText=Item->text();
        if(QFile::exists(ItemText))
        {
                emit SendFileName(ItemText);
                return ;
        }
        if(ItemText.isEmpty())
        {
                return ;
        }
        QStringList lineInfo;
        lineInfo=ItemText.split(":");
        lineNum=lineInfo[0].toInt();
        rownum=ui.ShowFindResult->row(Item);
        for(register int i=rownum-1;i>=0;i--)
        {
                QString filename=ui.ShowFindResult->item(i)->text();
                if(QFile::exists(filename))
                {
                        emit SendFileName(filename,lineNum);
                        return ;
                }
        }
}

void FindDir::OpenDirDialog(void)
{
	QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                 "/home",
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks);
	ui.DirText->setText(dir);
}

void FindDir::StartFindText(void)
{
	QString DirTextStr = ui.DirText->text();
	QString FindTextStr = ui.FindText->text();
	int CurrentIndex = ui.Suffix->currentIndex();

	if(DirTextStr.isEmpty())
	{
		QMessageBox::information(this,tr("Prompt"),
					tr("Directory is empty"));
		return ;
	}
	else if(FindTextStr.isEmpty())
	{
		QMessageBox::information(this,tr("Prompt"),
					tr("Find Text is empty"));
		return ;
	}
	/*
	奇怪的BUG？？
	const char*  DirTextChar = DirTextStr.toStdString().c_str();
	const char*  FindTextChar = FindTextStr.toStdString().c_str();
	*/
	const char* SuffixChar = SuffixArray[CurrentIndex];
	myregex(this,DirTextStr.toStdString().c_str(),FindTextStr.toStdString().c_str(),SuffixChar,ui.ShowFindResult);
}
